package me.caofeng.util;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import sun.invoke.empty.Empty;

import java.util.Optional;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;


/**
 * Copyright © 2017曹峰. All rights reserved.
 *
 * @Prject: mall
 * @Package: me.caofeng.util
 * @Description: 内存缓存工具类
 * @Author: 曹峰 blog.caofeng.me
 * @Date: 2017-06-18 13:20
 * @Version: V1.0
 */
public class CacheUtil {
    private static Logger LOGGER = LogManager.getLogger(CacheUtil.class);

    private static LoadingCache<String, Object> localCache = CacheBuilder
            .newBuilder().initialCapacity(1000)
            .maximumSize(100000)
            .expireAfterWrite(10, TimeUnit.MINUTES)
            .build(new CacheLoader<String, Object>() {
                @Override
                public String load(String s) throws Exception {
                    return null;
                }
            });

    /**
     * @Author:曹峰 blog.caofeng.me
     * @Date: 2017/6/18 17:38
     * @Description: 添加缓存
    */
    public static void putValue(String key, Object value) {
        localCache.put(key, value);
    }

    /**
     * @Author:曹峰 blog.caofeng.me
     * @Date: 2017/6/18 17:38
     * @Description: 获取缓存中的数据
    */
    public static Object getValue(String key) {
        Object value = null;
        try {
            value = localCache.get(key);
        } catch (Exception e) {
            LOGGER.error(e);
        }
        return value;
    }

    /**
     * @Author:曹峰 blog.caofeng.me
     * @Date: 2017/6/18 17:37
     * @Description: 清空缓存
    */
    public static void invalidate(String key){
       localCache.invalidate(key);
    }

    public static void main(String[] args){
        Cache<String ,Integer> cache = CacheBuilder
            .newBuilder()
            .expireAfterWrite(10, TimeUnit.MINUTES)
            .build();
        Integer couont = cache.getIfPresent("test");
        LOGGER.debug(couont);

    }

}

